#!/usr/bin/env node

const https = require('https');
const http = require('http');

// 文章数据结构Schema定义
const ARTICLE_SCHEMA = {
  id: 'number',
  title: 'string',
  pic: 'string',
  content: 'string',
  categoryId: 'number',
  isRecommend: 'boolean',
  createTime: 'string',
  viewCount: 'number',
  keywords: 'string',
  descript: 'string',
  author: 'string'
};

// 配置项Schema
const CONFIG_SCHEMA = {
  key: 'string',
  value: 'string'
};

console.log('🔍 检查摄影展小程序文章Schema...');
console.log('====================================================');

async function main() {
  try {
    // 1. 检查配置接口
    console.log('1. 检查系统配置接口...');
    await checkConfigAPI();

    // 2. 检查文章列表接口
    console.log('\n2. 检查文章列表接口...');
    await checkArticleListAPI();

    // 3. 检查网站统计接口
    console.log('\n3. 检查网站统计接口...');
    await checkSiteStatisticsAPI();

    console.log('\n✅ Schema检查完成!');
  } catch (error) {
    console.error('❌ 检查过程中出现错误:', error.message);
  }
}

function makeRequest(url, options = {}) {
  return new Promise((resolve, reject) => {
    const lib = url.startsWith('https://') ? https : http;
    const req = lib.request(url, options, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const parsed = JSON.parse(data);
          resolve(parsed);
        } catch (err) {
          resolve({ raw: data, error: 'JSON解析失败' });
        }
      });
    });

    req.on('error', reject);
    req.setTimeout(10000, () => {
      req.destroy();
      reject(new Error('请求超时'));
    });

    if (options.method === 'POST' && options.body) {
      req.write(options.body);
    }
    req.end();
  });
}

async function checkConfigAPI() {
  const url = 'https://api.it120.cc/photography/config/values?keys=mallName,mylogo,myname,tel';

  try {
    const response = await makeRequest(url);

    if (response.error) {
      console.log(`❌ 配置接口响应解析失败: ${response.error}`);
      console.log(`原始响应: ${response.raw}`);
      return;
    }

    if (response.code !== 0) {
      console.log(`❌ 配置接口返回错误: code=${response.code}, msg=${response.msg}`);
      return;
    }

    console.log(`✅ 配置接口正常，返回 ${response.data.length} 个配置项`);

    // 验证配置项Schema
    validateSchema(response.data[0], CONFIG_SCHEMA, '配置项');

    // 显示配置项
    response.data.forEach(config => {
      console.log(`   - ${config.key}: ${config.value}`);
    });

  } catch (error) {
    console.log(`❌ 请求配置接口失败: ${error.message}`);
  }
}

async function checkArticleListAPI() {
  const url = 'https://api.it120.cc/photography/cms/news/list';
  const postData = JSON.stringify({
    isRecommend: true,
    page: 1
  });

  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    },
    body: postData
  };

  try {
    const response = await makeRequest(url, options);

    if (response.error) {
      console.log(`❌ 文章列表接口响应解析失败: ${response.error}`);
      console.log(`原始响应: ${response.raw}`);
      return;
    }

    if (response.code !== 0) {
      console.log(`❌ 文章列表接口返回错误: code=${response.code}, msg=${response.msg}`);
      return;
    }

    console.log(`✅ 文章列表接口正常，返回 ${response.data.length} 篇文章`);

    if (response.data.length > 0) {
      console.log('\n📄 文章Schema验证:');
      validateSchema(response.data[0], ARTICLE_SCHEMA, '文章');

      console.log('\n📋 文章列表预览:');
      response.data.slice(0, 3).forEach((article, index) => {
        console.log(`   ${index + 1}. ${article.title} (ID: ${article.id}, 浏览: ${article.viewCount || 0})`);
      });

      if (response.data.length > 3) {
        console.log(`   ... 还有 ${response.data.length - 3} 篇文章`);
      }
    } else {
      console.log('   📭 暂无文章数据');
    }

  } catch (error) {
    console.log(`❌ 请求文章列表接口失败: ${error.message}`);
  }
}

function validateSchema(data, schema, typeName) {
  console.log(`   检查${typeName}字段:`);

  Object.keys(schema).forEach(key => {
    const expectedType = schema[key];
    const actualValue = data[key];
    const actualType = typeof actualValue;

    let status = '✅';
    let message = '';

    if (actualValue === undefined || actualValue === null) {
      status = '⚠️';
      message = '(缺失)';
    } else if (actualType !== expectedType) {
      status = '❌';
      message = `(期望: ${expectedType}, 实际: ${actualType})`;
    } else if (expectedType === 'string' && actualValue === '') {
      status = '⚠️';
      message = '(空字符串)';
    } else if (expectedType === 'number' && actualValue === 0) {
      status = '⚠️';
      message = '(值为0)';
    }

    console.log(`   ${status} ${key.padEnd(15)} (${expectedType}): ${actualValue} ${message}`);
  });

  // 检查额外字段
  const extraFields = Object.keys(data).filter(key => !schema.hasOwnProperty(key));
  if (extraFields.length > 0) {
    console.log('   📝 额外字段:');
    extraFields.forEach(key => {
      console.log(`   ➕ ${key.padEnd(15)} (${typeof data[key]}): ${data[key]}`);
    });
  }
}

async function checkSiteStatisticsAPI() {
  const url = 'https://api.it120.cc/photography/site/statistics';

  try {
    const response = await makeRequest(url);

    if (response.error) {
      console.log(`❌ 网站统计接口响应解析失败: ${response.error}`);
      console.log(`原始响应: ${response.raw}`);
      return;
    }

    if (response.code !== 0) {
      console.log(`❌ 网站统计接口返回错误: code=${response.code}, msg=${response.msg}`);
      return;
    }

    console.log(`✅ 网站统计接口正常`);
    console.log('📊 统计数据结构:');
    console.log(JSON.stringify(response.data, null, 2));

    // 检查预期的字段
    const expectedPaths = [
      'dfs.count',
      'cmsArticle.numbers',
      'cmsArticle.views'
    ];

    expectedPaths.forEach(path => {
      const value = getNestedValue(response.data, path);
      const status = value !== undefined ? '✅' : '❌';
      console.log(`   ${status} ${path.padEnd(20)}: ${value}`);
    });

  } catch (error) {
    console.log(`❌ 请求网站统计接口失败: ${error.message}`);
  }
}

function getNestedValue(obj, path) {
  return path.split('.').reduce((current, key) => {
    return current && current[key] !== undefined ? current[key] : undefined;
  }, obj);
}

// 运行主函数
main().catch(console.error);